<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI虚拟主播 - Live2D渲染器 (可调节版)</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            /* 纯绿色背景 - 用于OBS色度键抠像 */
            background: #00FF00;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            overflow: hidden;
        }
        
        #canvas-container {
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        /* 控制面板 */
        #control-panel {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.85);
            color: white;
            padding: 20px;
            border-radius: 10px;
            font-size: 14px;
            min-width: 300px;
            z-index: 1000;
        }
        
        #control-panel h3 {
            margin: 0 0 15px 0;
            color: #4CAF50;
        }
        
        .control-group {
            margin: 15px 0;
        }
        
        .control-group label {
            display: block;
            margin-bottom: 5px;
            color: #aaa;
        }
        
        .control-group input[type="range"] {
            width: 100%;
            margin: 5px 0;
        }
        
        .control-group .value-display {
            display: inline-block;
            min-width: 60px;
            text-align: right;
            color: #4CAF50;
            font-weight: bold;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .button {
            flex: 1;
            padding: 8px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .button:hover {
            background: #45a049;
        }
        
        .button.secondary {
            background: #666;
        }
        
        .button.secondary:hover {
            background: #555;
        }
        
        #toggle-panel {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 10px 15px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            z-index: 1001;
        }
        
        #subtitle {
            position: absolute;
            bottom: 50px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px 40px;
            border-radius: 15px;
            font-size: 24px;
            text-align: center;
            max-width: 80%;
            z-index: 1000;
            display: none;
        }
    </style>
</head>
<body>
    <div id="canvas-container"></div>
    
    <!-- 控制面板 -->
    <div id="control-panel">
        <h3>🎮 模型调节面板</h3>
        
        <div class="control-group">
            <label>📏 缩放大小: <span class="value-display" id="scale-value">1.5x</span></label>
            <input type="range" id="scale-slider" min="0.5" max="3.0" step="0.1" value="1.5">
        </div>
        
        <div class="control-group">
            <label>↔️ 水平位置: <span class="value-display" id="x-value">50%</span></label>
            <input type="range" id="x-slider" min="0" max="100" step="1" value="50">
        </div>
        
        <div class="control-group">
            <label>↕️ 垂直位置: <span class="value-display" id="y-value">70%</span></label>
            <input type="range" id="y-slider" min="0" max="100" step="1" value="70">
        </div>
        
        <div class="button-group">
            <button class="button" onclick="resetPosition()">重置</button>
            <button class="button secondary" onclick="saveSettings()">保存设置</button>
        </div>
        
        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #444; font-size: 12px; color: #888;">
            💡 提示: 调整后的参数会自动应用<br>
            按 H 键隐藏/显示此面板
        </div>
    </div>
    
    <button id="toggle-panel" onclick="togglePanel()">隐藏面板 (H)</button>
    
    <div id="subtitle"></div>

    <!-- 加载本地库文件 -->
    <script src="/libs/live2dcubismcore.min.js?v=2"></script>
    <script src="/libs/pixi.min.js?v=2"></script>
    <script src="/libs/pixi-live2d-display-cubism4.min.js?v=2"></script>

    <script>
        // 全局变量
        let app = null;
        let model = null;
        let ws = null;
        
        // 模型参数
        let modelScale = 1.5;
        let modelXPercent = 50;
        let modelYPercent = 70;

        // 初始化
        async function init() {
            try {
                console.log('✓ PIXI.js 已加载:', PIXI.VERSION);
                console.log('✓ Cubism 4 Core 已加载:', Live2DCubismCore.Version.csmGetVersion());
                console.log('✓ pixi-live2d-display (Cubism4) 已加载');

                // 将 PIXI 暴露到 window
                window.PIXI = PIXI;

                // 创建 PIXI 应用
                app = new PIXI.Application({
                    width: window.innerWidth,
                    height: window.innerHeight,
                    backgroundColor: 0x00FF00,
                    backgroundAlpha: 1,
                    antialias: true,
                    resolution: window.devicePixelRatio || 1,
                    autoDensity: true,
                });

                document.getElementById('canvas-container').appendChild(app.view);
                console.log('✓ PIXI应用已创建');

                // 加载模型
                await loadModel();

                // 连接 WebSocket
                connectWebSocket();

                // 设置控制器
                setupControls();

                // 加载保存的设置
                loadSettings();

                // 键盘快捷键
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'h' || e.key === 'H') {
                        togglePanel();
                    }
                });

                // 窗口大小变化
                window.addEventListener('resize', onResize);

            } catch (error) {
                console.error('初始化失败:', error);
                alert('初始化失败: ' + error.message);
            }
        }

        // 加载模型
        async function loadModel() {
            try {
                console.log('开始加载模型...');
                const modelPath = '/models/hiyori/runtime/hiyori_free_t08.model3.json';

                model = await PIXI.live2d.Live2DModel.from(modelPath, {
                    autoInteract: true,
                    autoUpdate: true,
                });

                console.log('✓ 模型加载成功');

                // 初始位置
                updateModelTransform();

                app.stage.addChild(model);
                console.log('✓ 模型已添加到舞台');

                // 播放待机动画
                if (model.internalModel && model.internalModel.motionManager) {
                    model.motion('idle');
                }

                // 点击事件
                model.on('hit', (hitAreas) => {
                    if (hitAreas.includes('body') || hitAreas.includes('Body')) {
                        model.motion('tap_body');
                    } else if (hitAreas.includes('head') || hitAreas.includes('Head')) {
                        model.motion('shake');
                    }
                });

            } catch (error) {
                console.error('模型加载失败:', error);
                throw error;
            }
        }

        // 更新模型变换
        function updateModelTransform() {
            if (!model) return;

            const baseScale = Math.min(
                window.innerWidth / model.width,
                window.innerHeight / model.height
            );

            model.scale.set(baseScale * modelScale);
            model.x = window.innerWidth * (modelXPercent / 100);
            model.y = window.innerHeight * (modelYPercent / 100);
            model.anchor.set(0.5, 0.5);
        }

        // 设置控制器
        function setupControls() {
            const scaleSlider = document.getElementById('scale-slider');
            const xSlider = document.getElementById('x-slider');
            const ySlider = document.getElementById('y-slider');

            scaleSlider.addEventListener('input', (e) => {
                modelScale = parseFloat(e.target.value);
                document.getElementById('scale-value').textContent = modelScale.toFixed(1) + 'x';
                updateModelTransform();
            });

            xSlider.addEventListener('input', (e) => {
                modelXPercent = parseInt(e.target.value);
                document.getElementById('x-value').textContent = modelXPercent + '%';
                updateModelTransform();
            });

            ySlider.addEventListener('input', (e) => {
                modelYPercent = parseInt(e.target.value);
                document.getElementById('y-value').textContent = modelYPercent + '%';
                updateModelTransform();
            });
        }

        // 重置位置
        function resetPosition() {
            modelScale = 1.5;
            modelXPercent = 50;
            modelYPercent = 70;

            document.getElementById('scale-slider').value = modelScale;
            document.getElementById('x-slider').value = modelXPercent;
            document.getElementById('y-slider').value = modelYPercent;

            document.getElementById('scale-value').textContent = modelScale.toFixed(1) + 'x';
            document.getElementById('x-value').textContent = modelXPercent + '%';
            document.getElementById('y-value').textContent = modelYPercent + '%';

            updateModelTransform();
        }

        // 保存设置
        function saveSettings() {
            const settings = {
                scale: modelScale,
                x: modelXPercent,
                y: modelYPercent
            };
            localStorage.setItem('live2d_settings', JSON.stringify(settings));
            alert('✓ 设置已保存!');
        }

        // 加载设置
        function loadSettings() {
            const saved = localStorage.getItem('live2d_settings');
            if (saved) {
                const settings = JSON.parse(saved);
                modelScale = settings.scale || 1.5;
                modelXPercent = settings.x || 50;
                modelYPercent = settings.y || 70;

                document.getElementById('scale-slider').value = modelScale;
                document.getElementById('x-slider').value = modelXPercent;
                document.getElementById('y-slider').value = modelYPercent;

                document.getElementById('scale-value').textContent = modelScale.toFixed(1) + 'x';
                document.getElementById('x-value').textContent = modelXPercent + '%';
                document.getElementById('y-value').textContent = modelYPercent + '%';

                updateModelTransform();
            }
        }

        // 切换面板显示
        function togglePanel() {
            const panel = document.getElementById('control-panel');
            const btn = document.getElementById('toggle-panel');
            
            if (panel.style.display === 'none') {
                panel.style.display = 'block';
                btn.textContent = '隐藏面板 (H)';
            } else {
                panel.style.display = 'none';
                btn.textContent = '显示面板 (H)';
            }
        }

        // WebSocket连接
        function connectWebSocket() {
            const wsUrl = 'ws://localhost:8765';
            ws = new WebSocket(wsUrl);

            ws.onopen = () => {
                console.log('✓ WebSocket 已连接');
                ws.send(JSON.stringify({ type: 'ready' }));
            };

            ws.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    handleWebSocketMessage(data);
                } catch (error) {
                    console.error('解析消息失败:', error);
                }
            };

            ws.onerror = (error) => {
                console.error('WebSocket 错误:', error);
            };

            ws.onclose = () => {
                console.log('WebSocket 断开,5秒后重连...');
                setTimeout(connectWebSocket, 5000);
            };
        }

        // 处理WebSocket消息
        function handleWebSocketMessage(data) {
            if (!model || !model.internalModel) return;

            const { type } = data;

            if (type === 'update_params') {
                const { params } = data;
                const coreModel = model.internalModel.coreModel;
                
                if (coreModel) {
                    if (params.mouthOpen !== undefined) {
                        coreModel.setParameterValueById('ParamMouthOpenY', params.mouthOpen);
                    }
                    if (params.angleX !== undefined) {
                        coreModel.setParameterValueById('ParamAngleX', params.angleX);
                    }
                    if (params.angleY !== undefined) {
                        coreModel.setParameterValueById('ParamAngleY', params.angleY);
                    }
                    if (params.eyeLOpen !== undefined) {
                        coreModel.setParameterValueById('ParamEyeLOpen', params.eyeLOpen);
                    }
                    if (params.eyeROpen !== undefined) {
                        coreModel.setParameterValueById('ParamEyeROpen', params.eyeROpen);
                    }
                }
            } else if (type === 'speak') {
                const { text, duration } = data;
                showSubtitle(text, duration);
            } else if (type === 'motion') {
                const { motion } = data;
                if (model.internalModel && model.internalModel.motionManager) {
                    model.motion(motion);
                }
            }
        }

        // 显示字幕
        function showSubtitle(text, duration = 3000) {
            const subtitle = document.getElementById('subtitle');
            subtitle.textContent = text;
            subtitle.style.display = 'block';

            setTimeout(() => {
                subtitle.style.display = 'none';
            }, duration);
        }

        // 窗口大小变化
        function onResize() {
            if (!app || !model) return;
            app.renderer.resize(window.innerWidth, window.innerHeight);
            updateModelTransform();
        }

        // 页面加载
        window.addEventListener('load', init);
    </script>
</body>
</html>
